import { getEntireData } from '@/services'
import {createAsyncThunk, createSlice} from '@reduxjs/toolkit'

const slice = createSlice({
    name: 'entire',
    initialState: {
        entireList: null,  //更多界面房间列表
        totalCount: 0,     //房间总数
        currentPage: 0,    //当前所在页码 0开始
        loading: false     //是否正在请求数据
    },
    reducers: {
        changeEntireListAction(state, {payload}) {
            state.entireList = payload
        },
        changeTotalCountAction(state, {payload}) {
            state.totalCount = payload
        },
        changeCurrentPageAction(state, {payload}) {
            state.currentPage = payload
        },
        changeLoadingAction(state, {payload}){
            state.loading = payload
        }
    }
})
/**
 * page: 当前页码 0开始
 * size: 每页所需多少条数据
 */
export const fetchEntireDataAction = createAsyncThunk(
    "fetchEntireData",
    async ({page = 0, size = 20}, {dispatch}) => {
        // 后端接口为偏移量起始位置 + 条数 来请求数据
        const offset = page * size 
        // 准备请求数据 修改loading = true
        dispatch(changeLoadingAction(true))
        const {list, totalCount} = await getEntireData(offset, size)
        // 数据请求完毕 修改loading = false
        dispatch(changeLoadingAction(false))
        // 修改当前页码
        dispatch(changeCurrentPageAction(page))
        // 修改房间列表数据
        dispatch(changeEntireListAction(list))
        // 修改所有房间总数
        dispatch(changeTotalCountAction(totalCount))
    }
)

export const {
    changeEntireListAction,
    changeTotalCountAction,
    changeCurrentPageAction,
    changeLoadingAction
} = slice.actions
export default slice.reducer

